<template>
    <div class="visitation-content">
        <cardBox title="模板库" icon="&#xe6f2;" class="left">
            <template #right>
                <el-button 
                    type="primary" 
                    icon="el-icon-plus" 
                    size="small"
                    @click="handleShowTempDialog()">
                    新建模板
                </el-button>
            </template>
            <div class="template-list">
                <div 
                    v-for="item in TempTreeList" 
                    :key="item.tempID" 
                    :class="['template-item', { 'active': currentBoxId === item.tempID }]"
                    @click="handleChangeTempTreeItem(item)">
                    <div class="template-icon">
                        <i class="el-icon-document"></i>
                    </div>
                    <div class="template-info">
                        <h4>{{ item.name }}</h4>
                    </div>
                    <div class="template-actions">
                        <el-tooltip content="编辑" placement="top">
                            <el-button 
                                icon="el-icon-edit" 
                                size="mini" 
                                circle
                                @click.stop="handleShowTempDialog(item)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button 
                                icon="el-icon-delete" 
                                size="mini" 
                                circle
                                type="danger"
                                @click.stop="handleDelAsTempDialog(item)"></el-button>
                        </el-tooltip>
                    </div>
                </div>
            </div>
        </cardBox>

        <cardBox :title="`当前模板: ${CurrentTemplateName }`" class="right">
            <div class="tree-wrapper">
                <treeMenu :treeData="menuTree" name="lable" ref="treeMenu" v-if="menuTree.length > 0" isRightMenu
                @addMenuItem="handleAddMenubyTemp"
                @delMenuItem="handleDelTreeMenubyTemp"
                @editMenuItem="handleAddMenubyTemp"/>
                <noData showMenu v-else/>
            </div>
        </cardBox>

        <el-dialog title="巡视项目" :visible.sync="dialogTempVisibleAdd" width="500px" v-dialogDrag :before-close="handleCancelTemp">
            <div class="dialog-content">
                <el-form class="templateForm" ref="templateForm" :model="templateForm" label-width="100px" :rules="templateRules">
                    <el-form-item label="项目名称" required prop="name">
                        <el-input placeholder="请输入巡视项目名称" v-model="templateForm.name"></el-input>
                        <div class="form-tip">建议使用清晰明确的名称便于后续识别</div>
                    </el-form-item>
                </el-form>
                
                <div class="dialog-footer">
                    <el-button @click="handleCancelTemp" size="small" class="cancel-btn" icon="el-icon-close" round>取消</el-button>
                    <el-button type="primary" size="small" @click="handleSaveTemp" class="confirm-btn" icon="el-icon-check" round :disabled="!templateForm.name">保存配置</el-button>
                </div>
            </div>
        </el-dialog>


        <el-dialog title="目录配置" :visible.sync="dialogMenuVisibleByTemp" width="500px" v-dialogDrag :before-close="handleCancelMenuByTemp">
            <div class="dialog-content">
                <el-form :model="menuFormByTemp" label-width="100px" size="medium" class="menu-form">
                <el-form-item label="目录名称" required>
                    <el-input 
                    v-model="menuFormByTemp.treeName" 
                    placeholder="请输入目录名称"
                    prefix-icon="el-icon-tickets"
                    clearable
                    ></el-input>
                </el-form-item>
                
                <el-form-item label="检查内容">
                    <el-input 
                    v-model="menuFormByTemp.request" 
                    placeholder="请输入检查内容描述" 
                    type="textarea"
                    :rows="5"
                    resize="none"
                    show-word-limit
                    maxlength="500"
                    ></el-input>
                    <div class="form-tip">详细描述此目录对应的检查内容和要求</div>
                </el-form-item>
                
                <el-form-item label="是否最底层" class="form-item-custom switch-item"> 
                    <el-switch 
                    v-model="menuFormByTemp.isBottom" 
                    active-color="#13ce66" 
                    inactive-color="#ff4949"  
                    :active-value="1" 
                    :inactive-value="0"
                    active-text="是最底层"
                    inactive-text="非最底层"
                    ></el-switch>
                    <div class="form-tip">设置为最底层目录后不可再添加子级目录</div>
                </el-form-item>
                </el-form>
                
                <div class="dialog-footer">
                <el-button 
                    @click="handleCancelMenuByTemp" 
                    size="small" 
                    class="cancel-btn"
                    icon="el-icon-close"
                    round
                >取消</el-button>
                <el-button 
                    type="primary" 
                    @click="handleSaveMenuByTemp" 
                    size="small" 
                    class="confirm-btn"
                    icon="el-icon-check"
                    round
                    :disabled="!menuFormByTemp.treeName"
                >保存配置</el-button>
                </div>
            </div>
            </el-dialog>
    </div>
</template>
<script>
import {getInspectionTemps, GetInspectionTempTrees, InspectionTempDel,InspectionTempAdd,InspectionTempEdit,InspectionTempTreeEdit,InspectionTempTreeAdd,InspectionTempTreeDel } from '../../api/https'
import bus from '@/utils/eventBus.js';
import treeMenu from '@/components/base/treeMenu.vue'
import noData from '@/components/base/noData.vue'
import cardBox from "../../components/base/cardBox.vue";
export default {
    name: 'visitationSetting',
    components: { treeMenu,noData,cardBox },
    data() {
        return {
            stationId: sessionStorage.getItem("stationId"),
            TempTreeList: [],
            currentBoxId: '',
            menuTree:[],
            dialogTempVisibleAdd:false,
            templateForm:{},
            editTempForm:false,
            templateRules:{
                name:[{required: true,message:'请输入名称'}],
            },
            treeDataEditByTemp:false,
            treeNodeLevelByTemp:'',
            CurrentTemplateName:'',
            menuFormByTemp:{},
            dialogMenuVisibleByTemp:false
        }
    },
    mounted() {
        this.initBasin()
        this.getInspectionTemp()
    },
    activated() {
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.stationId = newStationId;
            this.getInspectionTemp()
        }
    },
    deactivated() {
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy() {
        bus.$off('station-changed', this.handleStationChanged);
        this.$refs.templateAsForm && this.$refs.templateAsForm.resetFields();
    },
    methods: {
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.getInspectionTemp()
            }
        },
        getInspectionTemp() {
            getInspectionTemps().then(res => {
                if (res.isSuccess) {
                    this.TempTreeList = res.data && res.data.length > 0 ? res.data : [];
                    this.currentBoxId = this.TempTreeList[0]?.tempID || '';
                    this.CurrentTemplateName = this.TempTreeList[0]?.name || '未选择模板'
                    if (this.currentBoxId) this.getTreeData();
                } else {
                    this.TempTreeList = [];
                }
            })
        },
        handleChangeTempTreeItem(data) {
            this.currentBoxId = data.tempID;
            this.CurrentTemplateName = data.name
            this.getTreeData();
        },
        getTreeData() {
            GetInspectionTempTrees({
                TempID: this.currentBoxId
            }).then(res => {
                if(res.isSuccess){
                    this.menuTree = res.data || []
                }else{
                    this.menuTree = []
                }
            })
        },
        handleShowTempDialog(data){
           if(data){
                this.editTempForm = true
                this.templateForm = {...data}
                
           }else{
                this.editTempForm = false
                this.templateForm = {}
           }
           this.dialogTempVisibleAdd = true
        },
        handleCancelTemp(){
            this.dialogTempVisibleAdd = false
            this.editTempForm = false
            this.templateForm = {}
        },
        handleDelAsTempDialog(data){
            this.$confirm(`确认删除名称为${data.name}的模板？`,'提示',{
                type:'warning'
            }).then(() => {
                InspectionTempDel({
                    TempID:data.tem
                }).then(res=>{
                if(res.isSuccess){
                    this.getInspectionTemp()
                }else{
                    this.$message.error(res.errorMessage)
                }
                })
            }).catch(() => {}); 
        },
        handleSaveTemp(){
            this.$refs['templateForm'].validate((valid) => {
                if (valid) {
                    if(this.editTempForm){
                        InspectionTempEdit(this.templateForm).then(res=>{
                            if(res.isSuccess){
                                this.handleCancelTemp()
                                this.getInspectionTemp()
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                            })
                    }else{
                        const data = {
                            tempID:0,
                            name:this.templateForm.name,
                            category:1
                        }
                        InspectionTempAdd(data).then(res=>{
                            if(res.isSuccess){
                                this.handleCancelTemp()
                                this.getInspectionTemp()
                            }else{
                            this.$message.error(res.errorMessage)
                            }
                        })
                    }
                } else {
                    return false;
                }
            })
        },
        handleAddMenubyTemp(data,isEdit,treeNodeLevel){
            this.treeDataEditByTemp = isEdit
            this.treeNodeLevelByTemp = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                this.menuFormByTemp = {..._editData}
            }else{
                if(data.node.isBottom && treeNodeLevel == 2){
                    this.$message.error('此目录已经是最底层，不能增加子级目录！')
                    return false
                }else{
                    this.menuFormByTemp = {
                        id: 0,
                        treeID:0,
                        treeName:'',
                        upTree: treeNodeLevel == 1 ? data.node.upTree || 0 : data.node.treeID,
                        isBottom:0,
                        valueID:0,
                        tempID:this.currentBoxId || 0,
                        category:1
                    }
                }
            }
            this.dialogMenuVisibleByTemp = true
        },
        handleDelTreeMenubyTemp(data){
            this.$confirm(`确认删除名称为 ${data.lable} 的节点？`,'提示',{
                type:'warning'
            }).then(() => {
                InspectionTempTreeDel({ID:data.node.id}).then(res=>{
                    if(res.isSuccess){
                    this.getTreeData()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {}); 
        },

        handleSaveMenuByTemp(){
            if(this.treeDataEditByTemp){
                InspectionTempTreeEdit(this.menuFormByTemp).then((res)=>{
                    if(res.isSuccess){
                        this.getTreeData()
                        this.handleCancelMenuByTemp()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                const data = {
                    ...this.menuFormByTemp,
                    tempID:this.currentBoxId,
                    valueID:0,
                    category:1
                }
                InspectionTempTreeAdd(data).then((res)=>{
                    if(res.isSuccess){ 
                        this.getTreeData()
                        this.handleCancelMenuByTemp()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleCancelMenuByTemp(){
            this.dialogMenuVisibleByTemp =false
            this.menuFormByTemp = {}
            this.treeDataEditByTemp = false
            this.treeNodeLevelByTemp = ''
        }
    }
}
</script>
<style scoped lang="scss">
.visitation-content {
    display: flex;
    flex-direction: row;
    justify-content: start;
    margin-top: -10px;
    height: calc(100vh - 110px);
    .left{
        width: 460px;
    }
    .right{
        flex:1;
        margin-left: 10px;
    }
}

.template-list {
    overflow-y: auto;
    padding: 16px;
    height: calc(100vh - 190px);
}

.template-item {
    display: flex;
    align-items: center;
    padding: 16px;
    margin-bottom: 12px;
    border-radius: 8px;
    border: 1px solid #ebeef5;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

.template-item:hover {
    border-color: #409eff;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.template-item.active {
    border-color: #409eff;
    background: linear-gradient(135deg, #ecf5ff 0%, #f0f7ff 100%);
}

.template-icon {
    margin-right: 12px;
    color: #409eff;
    font-size: 20px;
}

.template-info h4 {
    margin: 0 0 4px 0;
    color: #303133;
    font-size: 14px;
}

.template-info p {
    margin: 0;
    color: #909399;
    font-size: 12px;
}


.template-actions {
    margin-left: auto;
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.template-item:hover .template-actions {
    opacity: 1;
}

.tree-wrapper{
    height: calc(100vh - 200px);
    overflow: auto;  
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>